<?php

function scanRemoteDir($storageServer = ''){
   if( !isset($storageServer['dirpath'])){
      return false;
   }
   global $baseServerInfo,$serverRsyncDir;
   $remoteDir = sprintf($serverRsyncDir, $storageServer['outip'], $storageServer['dirpath']);
   $remoteDir = explode(':', $remoteDir);
   $remoteDir = $remoteDir[0];
   $cmd = sprintf('/usr/bin/ssh %s /bin/ls %s', $remoteDir, $storageServer['dirpath']);
   if($baseServerInfo['outip'] == $storageServer['outip']){
      $cmd = sprintf('/bin/ls %s', $storageServer['dirpath']);
   }
   exec($cmd, $list);
   $avlist = array();
   if( !is_array($list)){
      return $avlist;
   }
   foreach($list as $val){
      $finfo = pathinfo($val);

      if( $finfo['extension'] == 'jpg' ){
         continue;
      }

      $avlist[] = $finfo['filename'];
   }
   return $avlist;
}

function deleteAvFilesByAvkey($data = ''){
   if( !isset($data['avkey'])){
      return false;
   }
   global $baseServerInfo,$storageServer,$serverRsyncDir,$coverTypeList,$avExtArr;
   $status = $flag = 1;
   //刪除命令
   $remoteDir = sprintf($serverRsyncDir, $storageServer['outip'], $storageServer['dirpath']);
   $remoteDir = explode(':', $remoteDir);
   $remoteDir = $remoteDir[0];
   $cmd = sprintf('/usr/bin/ssh %s /bin/rm -f %s', $remoteDir, $storageServer['dirpath']);
   if($baseServerInfo['outip'] == $storageServer['outip']){
      $cmd = sprintf('/bin/rm -f %s', $storageServer['dirpath']);
   }

//   var_dump($cmd);exit;

   //刪除文件
  if(strlen($data['avkey']) < 2){
      echo "\ngg\n";
      return false;
  }
      
    $avkey = $data['avkey'];

   if(isset($data['bkey']) && strlen($data['bkey']) > 4){
      // B面
      $shell = sprintf($cmd.'/%s.*',$data['bkey']);
      system($shell, $flag);
      $status = $status && !$flag;
   }

      $shell = sprintf($cmd.'/%s.*', $avkey);
      echo $shell."\n";
      system($shell, $flag);
      $status = $status && !$flag;
   
   //封面 
   foreach($coverTypeList as $type){
      $shell = sprintf($cmd.'/%s-%s.jpg', $avkey, $type);
      @system($shell, $flag);
      $status = $status && !$flag;
   }
   return $status;
}

function getDiskUseSize(){
   global $baseServerInfo,$storageServer,$serverRsyncDir;
   if( !isset($storageServer['dirpath'])){
      return 0;
   }
   $remoteDir = sprintf($serverRsyncDir, $storageServer['outip'], $storageServer['dirpath']);
   $remoteDir = explode(':', $remoteDir);
   $remoteDir = $remoteDir[0];
   $cmd = sprintf('/usr/bin/ssh %s /bin/df  %s', $remoteDir, $storageServer['dirpath']);
   if($baseServerInfo['outip'] == $storageServer['outip']){
      $cmd = sprintf('/bin/df %s', $storageServer['dirpath']);
   }
   @exec($cmd, $output, $return);
   $len = count($output);
   if(2 < $len){
      for($i = $len - 1; $i > 1; $i--){
         $output[$i -1] .= $output[$i];
         unset($output[$i]);
      }
   }
   if( !isset($output[1])){
      return false;
   }
   $tmp = preg_split('#\s+#',$output[1]);
/*
   array(6) {
  [0]=>
  string(28) "/dev/mapper/VolGroup-lv_root"
  [1]=>
  string(3) "97G"
  [2]=>
  string(3) "32G"
  [3]=>
  string(3) "60G"
  [4]=>
  string(3) "35%"
  [5]=>
  string(1) "/"
}
*/
   $tmp[1] /= 1024;
   $tmp[2] /= 1024;
   $return = array('total' => floor($tmp[1]), 'use' => ceil($tmp[2]));
//var_dump($tmp);exit;
   return $return;
}

function initBaseServerInfo($info){
   if( !isset($info['dirpath'])){
     die("\n======The baseServerInfo is Empty!=======\n");
   }
   global $baseServerInfo;
   $baseServerInfo = array('uploadsDir'      => sprintf("%s/uploadsVideo",$info['dirpath']),
                           'noneInfoDir'     => sprintf("%s/noneInfoVideo",$info['dirpath']),
                           'errorUploadsDir' => sprintf("%s/noneInfoVideo",$info['dirpath']),
                           'fixCoverDir'     => sprintf("%s/fixCoverImages",$info['dirpath']),
                           'outip'           => $info['outip']
   );
}

function getAvinfoByfanhao($fanhao = ''){
   if(!$fanhao){
      return false;
   }
   global $fanhaoPattern;
//支持跳轉
   $html = file_get_contents('http://tw.fanhao.org/search/'.urlencode($fanhao).'/'); 
   $info = array();
   preg_match($fanhaoPattern['fanhao'],$html,$match);
   if(!isset($match[1])){
      return false;
   }
   $info['avkey'] = $match[1];
   preg_match($fanhaoPattern['title'],$html,$match);
   $info['title'] = $match[1];
   preg_match($fanhaoPattern['publisher'],$html,$match);
   $info['publisher'] = $match[1];
   preg_match($fanhaoPattern['peoples'],$html,$match);
   $info['peoples'] = isset($match[1]) ? $match[1] : '';
   $info['peoples'] = preg_replace('#<a.+>#Uis','',$info['peoples']);
   $info['peoples'] = preg_replace('#</a>#Uis',',',$info['peoples']);
   $info['peoples'] = preg_replace('#,\s+#is',',',$info['peoples']);
   $info['peoples'] = trim($info['peoples'],','); 
   preg_match($fanhaoPattern['intro'],$html,$match);
   $info['intro'] = isset($match[1]) ? $match[1] : '';
   $info['intro'] = trim($info['intro']);
   $info['tags'] = '';
   return $info;
}

function getAvinfoByavkey($avkey = '' , $mode = 1, $downcover = 0){
   if(1 == $mode){
      $info = getAvinfoByfanhao($avkey);
      $data = getAvinfoBydmmco($avkey);
      if($info){
         $info['cover'] = $data['cover'];
         $info['tags'] = $data['tags'];
      }else{
         $info = $data ? $data : getAvinfoBysuperm($avkey);
      }
      if($info){
         $info['ismasked'] = 1;
      }
   }else{
      $info = getAvinfoByavent($avkey);
      if(!$info){
         $avkeynew = str_replace('-','',$avkey);
         $info = getAvinfoByavent($avkeynew);
         $info['avkey'] = $avkey;
      }
      if($info){
         $info['ismasked'] = 0;
      }
   }
   if(isset($info['peoples'])){
      $info['peoples'] = str_replace('未填寫','',$info['peoples']);
   }
   return $info;
}

/*
 *判断是否为图片
 *return 不是返回false、是返回size/w/h
*/
function check_img($realPath = null){
  $size = getimagesize($realPath);
  $type = strtolower($size['mime']);
  if("image/png" != $type && "image/jpeg" != $type && "image/gif" != $type && "image/bmp" !=$type){
    return false;
  }
  $imgsize = filesize($realPath);
  $flag = convertimg($realPath);
  if($flag)
    return false;

  $imginfo = array(
     'width' => $size[0],
     'height' => $size[1],
     'size' => $imgsize,
     'mime' => $size['mime']
  );
  return $imginfo;
}

function convertimg($realPath = null){
 return exec('convert -strip '.$realPath.' '.$realPath);
}

function getAvinfoByavent($avkey = ''){
   if(!$avkey){
      return false;
   }
   global $atmCurl;
   $atmCurl->config['url'] = sprintf('http://www.aventertainments.com/search_Products.aspx?languageID=2&dept_id=29&keyword=%s&searchby=keyword',$avkey);
   $html = $atmCurl->getHtml();
   $pattern = '#<td><h4><a href="[^"]+">(.+)</a>&nbsp;.*</h4>#Uis';
   preg_match($pattern,$html,$match);
   if(!isset($match[1])){
      return false;
   }
   $info = array();
   $info['title'] = $match[1];
   $pattern = '#<div class="list-product"><a href="([^"]+)">.*\s*<img src="([^"]+)" border="0" align="left"  /></a></div>#Uis';
   preg_match($pattern,$html,$match);
   $avurl = isset($match[1]) ? $match[1] : '';
   $info['cover'] = isset($match[2]) ? $match[2] : '';
   if($info['cover']){
      $info['cover'] = str_ireplace('product_images','bigcover',$info['cover']);
   }
   $pattern = '#女優名: (.+)<br>#Uis';
   preg_match($pattern,$html,$match);
   $info['peoples'] = isset($match[1]) ? $match[1] : '';
   $info['peoples'] = preg_replace('#<a.+>#Uis','',$info['peoples']);
   $info['peoples'] = preg_replace('#</a>#Uis',',',$info['peoples']);
   $info['peoples'] = preg_replace('#,\s+#is','',$info['peoples']);
   $info['peoples'] = trim($info['peoples'],','); 
   $pattern = '#スタジオ:<a href="[^"]+">(.+)</a><br />#Uis';
   preg_match($pattern,$html,$match);
   $info['publisher'] = $match[1];
   $pattern = '#<tr>\s+<td height="25">\s+(.+)\s+<a href="[^"]+"><u>詳細ページへ</u></a>\s+</td>\s+</tr>#Uis';
   preg_match($pattern,$html,$match);
   $info['intro'] = $match[1];
   $info['intro'] = trim($info['intro']);
   $info['avkey'] = $avkey;
   $info['tags'] = '';
   if($avurl){
      $atmCurl->config['url'] = $avurl;
      $html = $atmCurl->getHtml();
      preg_match('#<div id="detailbox">\s+<span class="title">カテゴリ一覧:</span>\s+<ul>(.+)</ul>\s*</div>#Uis',$html,$match);
      if(isset($match[1])){
         $info['tags'] = $match[1];
         $info['tags'] = preg_replace('#<ol><A href="[^"]+">#Uis','',$info['tags']);
         $info['tags'] = preg_replace('#</A></ol>\s+#Uis',',',$info['tags']);
         $info['tags'] = preg_replace('#\s+#','',$info['tags']);
         $info['tags'] = str_replace('・',',',$info['tags']);
         $info['tags'] = trim($info['tags'],',');
         $info['tags'] = checkIsChinese($info['tags']);
      }
   }
   return $info;
}

function getAvinfoBysuperm($avkey = ''){
   if(!$avkey){
      return false;
   }
   global $spmCurl;
   $info = array();
   $domain = 'http://supermm.jp';
   for($i = 0;$i<=1;$i++){
      $spmCurl->config['url'] = sprintf('http://supermm.jp/search/image/-_-/cate/20/word/%s',$avkey);
      $html = $spmCurl->getHtml();
      if(empty($html)){
         $spmCurl->config['referer'] = $spmCurl->config['url'];
         $spmCurl->config['url'] = $domain.'/ageauth';
         $html = $spmCurl->getHtml();
         $spmCurl->config['referer'] = $spmCurl->config['url'];
         $spmCurl->config['url'] = $domain.'/ageset/-_-/age/18';
         $html = $spmCurl->getHtml();
      }else{
         preg_match('#<div class="titlebox">\s+<p><a href="/detail/index/-_-/iid/([^"]+)">.+</a></p>\s+</div>#Uis',$html,$match);
         if( !isset($match[1])){
            return false;
         }
         $spmCurl->postVal = array();
         $spmCurl->config['referer'] = $spmCurl->config['url'];
         $spmCurl->config['url'] = $domain.'/detail/index/-_-/iid/'.$match[1];
         $html = $spmCurl->getHtml();
         preg_match('#<div class="hreview">\s+<h2>(.+)</h2>\s+</div>#Uis',$html,$match);
         if( !isset($match[1])){
            return false;
         }
         $info['title'] = $match[1];
         $info['avkey'] = $avkey;
         preg_match('#<dt>出演</dt>\s+<dd>\s+(.+)</dd>#Uis',$html,$match);
         $match[1] = isset($match[1]) ? $match[1] : '';
         $match[1] = preg_replace('#&nbsp;\s*#is','',$match[1]);
         $match[1] = preg_replace('#<a.*>#Uis','',$match[1]);
         $match[1] = preg_replace('#</a>#is',',',$match[1]);
         $match[1] = trim($match[1]);
         $info['peoples'] = trim($match[1],',');
         preg_match('#<dt>メーカー</dt>\s+<dd>(.+)</dd>#Uis',$html,$match);
         $match[1] = isset($match[1]) ? $match[1] : '';
         $match[1] = preg_replace('#&nbsp;\s*#is','',$match[1]);
         $match[1] = preg_replace('#<a.*>#Uis','',$match[1]);
         $match[1] = preg_replace('#</a>#is',',',$match[1]);
         $match[1] = trim($match[1]);
         $info['publisher'] = trim($match[1],',');
         preg_match('#<p class="comment2">(.+)</p>#Uis',$html,$match);
         $match[1] = isset($match[1]) ? $match[1] : '';
         $match[1] = preg_replace('#【DVD発売日.+】#Uis','',$match[1]);
         $info['intro'] = trim($match[1]);
         preg_match('#<div class="leftdetail">\s+<div class="jak borderImage">\s+<a href="([^"]+)" rel="enlarge_jkt" ><img src="[^"]+" .+ /></a>\s+</div>#Uis',$html,$match);
         $match[1] = isset($match[1]) ? $match[1] : '';
         $info['cover'] = $match[1];
         preg_match('#<dt>ジャンル</dt>\s+<dd>(.+)</dd>#Uis',$html,$match);
         $info['tags'] = '';
         if(isset($match[1])){
            $info['tags'] = $match[1];
            $info['tags'] = preg_replace('#<A.+>#Uis','',$info['tags']);
            $info['tags'] = preg_replace('#</A>&nbsp;\s*#Uis',',',$info['tags']);
            $info['tags'] = preg_replace('#\s+#','',$info['tags']);
            $info['tags'] = str_replace('・',',',$info['tags']);
            $info['tags'] = trim($info['tags'],',');
            $info['tags'] = checkIsChinese($info['tags']);
         }
         $info['director'] = '';
         return $info;
      }
   }
}

function checkIsChinese($str = '', $separator = ','){
   if( !$str){
      return false;
   }
   global $allowTags;
   $arr = explode($separator,$str);
   $tmp = array();
   foreach($arr as $v){
      $v = trim($v);
      if( in_array($v,$allowTags) ){
         $tmp[] = $v;
      }
   }
   $tmp = implode($separator,$tmp);
   return $tmp;
}

function getAvinfoBydmmco($avkey = ''){
   if(!$avkey){
      return false;
   }
   global $dmCurl;
   $info = array();
//從搜索結果找影片url
   $dmCurl->config['url'] = sprintf('http://www.dmm.co.jp/search/=/searchstr=%s/',$avkey);
   $html = $dmCurl->getHtml();
//   $html = iconv('EUC-JP','UTF-8',$html);
   $pattern = '#<p class="tmb">\s*<a href="http://www.dmm.co.jp([^"]+)">\s*<span class="img"><img src="[^"]+" alt="[^"]+"></span>\s*<span class="txt">.+</span>\s*</a>\s*</p>#Uis';
   preg_match($pattern,$html,$match);
   if(!isset($match[1])){
      return false;
   }
//從url中到詳情頁獲取信息
   $dmCurl->config['url'] = sprintf('http://www.dmm.co.jp%s',$match[1]);
   $html = $dmCurl->getHtml();
   $html = iconv('EUC-JP','UTF-8',$html);
   $pattern = '#<tr>\s+<td.*>出演者：</td>.+<td.*>.*<span id="performer">\s+(.+)\s+</td>.+</tr>#Uis';
   preg_match($pattern,$html,$match);
//   var_dump($match);exit;
   if(!isset($match[1])){
      return false;
   }
   $info['peoples'] = $match[1];
   $info['peoples'] = preg_replace('#<a.+>#Uis','',$info['peoples']);
   $info['peoples'] = preg_replace('#</a>#Uis',',',$info['peoples']);
   $info['peoples'] = preg_replace('#,\s+#is',',',$info['peoples']);
   $info['peoples'] = trim($info['peoples'],','); 
   $info['peoples'] = preg_replace('#[-]+#is','',$info['peoples']);
   $pattern = '#<div class="hreview">.*<h1 .*class="item fn".*>(.+)</h1></div>#Uis';
   preg_match($pattern,$html,$match);
   $info['title'] = trim(strip_tags($match[1]));
   $pattern = '#<tr>\s+<td.*>監督：</td>\s+<td.*><a href="[^"]+">(.+)</a></td>\s+</tr>#Uis';
   preg_match($pattern,$html,$match);
   $info['director'] = isset($match[1]) ? $match[1] : '';
   $pattern = '#<tr>\s+<td.*>メーカー：</td>\s+<td.*><a href="[^"]+">(.+)</a></td>\s+</tr>#Uis';
   preg_match($pattern,$html,$match);
   $info['publisher'] = isset($match[1]) ? $match[1] : '';
   $pattern = '#<td.*>ジャンル：</td>\s+<td.*>(.+)</td>#Uis';
   preg_match($pattern,$html,$match);
   if(isset($match[1])){
      $match[1] = preg_replace('#<a.+>#Uis','',$match[1]);
      $match[1] = preg_replace('#</a>#Uis',',',$match[1]);
      $match[1] = preg_replace('#\s+#is','',$match[1]);
      $match[1] = str_replace(array('&nbsp;','・'),array('',','),$match[1]);
      $match[1] = trim($match[1],',');
   }else{
      $match[1] = '';
   }
   $info['tags'] = checkIsChinese($match[1]);
   $info['avkey'] = $avkey;
   $pattern = '#<div class="[^"]*mg-b20[^"]*">\s*<p class="[^"]*mg-b20[^"]*">(.+)\s*</div>#Uis'; 
   preg_match($pattern,$html,$match);
   $info['intro'] = isset($match[1]) ? trim(strip_tags($match[1])) : '';
   $pattern = '#<a href="([^"]+)" [^>]*name="package-image"[^>]*>イメージを拡大</a>#Uis';
   preg_match($pattern,$html,$match);
   $info['cover'] = isset($match[1]) ? $match[1] : '';
   
   return $info;
}

function downImg($url = '', $local = ''){
   if(!$url || !$local){
      return false;
   }
   $cmd = sprintf('wget -t 2 -T 10 %s -O %s',$url,$local);
   @system($cmd);
   @chmod($local,0775);
   $status = check_img($local);
   if( isset($status['size']) && $status['size'] > 10000){
      return true;
   }
   @unlink($local);
   return false;
}

function moveFile($old = '', $new =''){
   if(!file_exists($old)){
      return false;
   }
   if(!file_exists($dir = dirname($new))){
      @mkdir($dir,0777,true);
   }
   if(!file_exists($dir)){
      echo "{$dir} 创建失败!\r\n";
      return false;
   }
   @rename($old,$new);
   $log = sprintf("\r\n%s 文件 %s 无信息!\r\n",date('Y-m-d H:i:s'),$new);
   addLog($log);
   return false;
}

function rsyncFile($local = ''){
  if(!file_exists($local)){
     echo "{$local} 文件不存在!\r\n";
     return false;
  }
  global $baseServerInfo,$storageServer,$serverRsyncDir;
  if( !isset($storageServer['serverid'])){
     die("\n=====The storageServer serverid is Empty!====\n");
  }
  $remoteDir = sprintf($serverRsyncDir, $storageServer['outip'], $storageServer['dirpath']);
  for($errcount = 0; $errcount <= 2; $errcount ++){
     $cmd = sprintf('/usr/bin/rsync -av %s %s', $local, $remoteDir);
     if($baseServerInfo['outip'] == $storageServer['outip']){
        $cmd = sprintf('/bin/mv -f %s %s',$local, $storageServer['dirpath']);
     }
//echo $cmd,"\n";exit;
     @system($cmd,$status);
     $status = !$status;
     if($status){
        break;
     }
     sleep(120);
  }
  if($status){
    @unlink($local);
    return true;
  }
  //將文件移到失敗區
  $fileInfo = pathinfo($local);
  $newName = sprintf('%s/%s/%s',$baseServerInfo['errorUploadsDir'],basename(dirname($fileInfo['dirname'])),basename($fileInfo['dirname']));
    
  $newName .= $fileInfo['basename'];
  moveFile($local,$newName);
  $log = sprintf("\r\n%s 文件 %s rsync傳輸失敗!\r\n",date('Y-m-d H:i:s'),$newName);
  addLog($log); 
  return false; 
}

function addLog($log = ''){
  global $logFile;
  if(!file_exists($logdir = dirname($logFile))){
     @mkdir($logdir,0777,true);
     if(!file_exists($logdir)){
        return false;
     }
  }
  file_put_contents($logFile,$log,FILE_APPEND);
}
function myScandir($dir = '',$filter = array()){
   if(!is_dir($dir)){
      echo $dir.": 目錄不存在\r\n";
      return false;
   }
   $dirList = scandir($dir);
   $fileInfo = $dirInfo = array();
   foreach($dirList as $v){
     if('.' == $v || '..' == $v){
        continue;
     }
     $path = rtrim($dir,'/').'/'.$v;
//echo $path,"\r\n";
     if(is_dir($path)){
       $dirInfo[] = $path;
     }else{
       if(is_array($filter) && count($filter) > 0){
          $info = pathinfo($path);
          if(!in_array(strtolower($info['extension']),$filter)){
             continue;
          }
       }
       $fileInfo[] = $path;
     }
   }
   return array('dir' => $dirInfo,'file' => $fileInfo);
}
